<!--
* description: 维修班组与技师设置
* author: xuliwen
* createdDate: 2021-01-29
-->
<template>
  <div id="twoTable" class="app-container app-container-table">
    <el-main class="leftMail MailOne">
      <one-table-template
        :ref="leftTable.tableRef"
        :key="leftTable.oneTableKey"
        :dynamic-buttons="leftTable.tableButtons"
        :dynamic-components="leftTable.tableComponents"
        :dynamic-api-config="leftTable.apiConfig"
        :dynamic-table-cols="leftTable.tableCols"
        :dynamic-form-fields="leftTable.formField"
        :dynamic-is-show-select="false"
        :dynamic-is-init-table="true"
        :callback-obj="leftTable.callbackObj"
        :dynamic-parent-table-ref="leftTable.tableRef"
        :dynamic-pager-count="5"
      />
    </el-main>
    <el-main class="rightElmain MailOne">
      <one-table-template
        :ref="rightTable.tableRef"
        :key="rightTable.oneTableKey"
        :dynamic-buttons="rightTable.tableButtons"
        :dynamic-components="rightTable.tableComponents"
        :dynamic-api-config="rightTable.apiConfig"
        :dynamic-table-cols="rightTable.tableCols"
        :dynamic-form-fields="rightTable.formField"
        :dynamic-un-form-fields="rightTable.unFormField"
        :dynamic-is-show-select="true"
        :dynamic-is-init-table="false"
        :callback-obj="rightTable.callbackObj"
        :dynamic-parent-table-ref="rightTable.tableRef"
        :dynamic-pager-count="5"
      />
    </el-main>
    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      @close="close"
    />
    <technicianEdit
      :key="technicianEditKey"
      :data-for-form="addRow"
      :popups-visible="technicianEditVisible"
      @sendCodeClose="sendCodeClose"
    />
  </div>
</template>
<script>
import { moreTableWithViewTemplateMixins } from '@/components/mixins/moreTableWithViewTemplateMixins'
import api from '@/api/se/apiBaseData'
import OneTableTemplate from '@/components/templates/oneTable'
import Edit from './edit'
import Vue from 'vue'
export default {
  name: 'TeamsTechnicianSetting',
  components: {
    OneTableTemplate,
    Edit,
    technicianEdit: () => import('./technicianEdit.vue')
  },
  // 组件混入对象
  mixins: [moreTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      ['lookupMamagerLeft', 'lookupMamagerRight'],
      function() {
        next()
      }
    )
  },
  data() {
    // 左网格pageCode
    const leftPageCode = 'lookupMamagerLeft'
    // 右网格pageCode
    const rightPageCode = 'lookupMamagerRight'
    // 绑定事件配置化事件
    // this.$ConfigCache.CacheConfig.bindEvent(this, [leftPageCode, rightPageCode])
    return {
      addRow: {},
      // 班组弹窗
      editPopupsVisible: false,
      editPopupsState: 'add',
      editPopupsKey: 'editPopupsKey',
      // 技师弹窗
      technicianEditVisible: false,
      technicianEditKey: 'technicianEditKey',
      editRowData: {},
      selectiondata: [],
      // 定义watch对象（用于组件联动监控）
      watchObj: [
        {
          formFieldName: 'leftTable.formField',
          tableComponentsName: 'leftTable.tableComponents',
          tableRef: 'leftTableRef'
        },
        {
          formFieldName: 'rightTable.formField',
          tableComponentsName: 'rightTable.tableComponents',
          tableRef: 'rightTableRef'
        }
      ],
      // 左网格
      leftTable: {
        // 网格Ref
        tableRef: 'leftTableRef',
        // 网格Key
        oneTableKey: 'leftTable',
        // 网格查询API配置对象
        apiConfig: api.teamsTechnicianSettingQueryTeam,
        // 动态组件-按钮
        tableButtons: [
          {
            compKey: 'btnKey1',
            type: 'primary',
            size: 'small',
            clickEvent: () => this.query(this.leftTable.tableRef),
            text: '查询',
            name: 'search', // 按钮图标样式
            position: 'right',
            fuzzySearch: true
          },
          {
            compKey: 'btnKey2',
            type: '',
            size: 'small',
            name: 'add',
            clickEvent: () => this.addTeam(),
            text: this.$t('sys.button.add'), // 新增
            position: 'left'
          }

        ],
        // 动态组件-查询条件
        tableComponents:
          this.$ConfigCache.CacheConfig.cacheData[leftPageCode] &&
          this.$ConfigCache.CacheConfig.cacheData[leftPageCode].tableComponents
            .length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[leftPageCode]
              .tableComponents
            : [
              {
                compKey: 'compKey1',
                span: 12,
                labelName: '班组名称：',
                codeField: 'groupName',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                isMust: true
              },
              {
                compKey: 'compKey2',
                span: 12,
                labelName: '班组类别：',
                codeField: 'workGroupType',
                component: () => import('@/components/org/LookupValue'),
                oFields: 'statusId,statusText',
                options: [
                  { statusId: '1', statusText: '机电班组' },
                  { statusId: '2', statusText: '钣喷班组' },
                  { statusId: '3', statusText: '质检班组' },
                  { statusId: '4', statusText: '清洁班组' }
                ],
                type: 'dropdownList',
                isMul: false,
                isMust: true
              }
            ],
        // 动态生成网格列
        tableCols:
          this.$ConfigCache.CacheConfig.cacheData[leftPageCode] &&
          this.$ConfigCache.CacheConfig.cacheData[leftPageCode].tableCols
            .length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[leftPageCode].tableCols
            : [
              {
                prop: 'repairGroupId',
                label: '班组ID',
                hidden: true,
                alwaysHidden: true
              },
              {
                prop: 'updateControlId',
                label: '并发控制ID',
                hidden: true,
                alwaysHidden: true
              },
              {
                prop: 'controlBtn1',
                label: '操作',
                minWidth: 180,
                isComponent: true,
                comps: [
                  {
                    compKey: 'propKey1',
                    labelName: '修改',
                    component: () => import('@/components/org/linkButton'),
                    clickEvent: (index) => this.edit(index)
                  },
                  {
                    compKey: 'propKey2',
                    labelName: '停用',
                    rowFileds: 'show:isEnableCn--停用',
                    component: () => import('@/components/org/linkButton'),
                    clickEvent: (index) => this.delet(index)
                  },
                  {
                    compKey: 'propKey3',
                    labelName: '启用',
                    rowFileds: 'show:isEnableCn--启用',
                    component: () => import('@/components/org/linkButton'),
                    clickEvent: (index) => this.delet(index)
                  }
                ]
              },
              {
                prop: 'workGroupCode',
                label: '班组编号',
                width: null,
                align: 'center'
              },
              {
                prop: 'groupName',
                label: '班组名称',
                width: null,
                align: 'center'
              },
              {
                prop: 'workGroupTypeCn',
                label: '班组类别',
                width: null,
                align: 'center'
              },
              {
                prop: 'isEnableCn',
                label: '状态',
                width: null,
                align: 'center'
              }
            ],
        // 表单查询数据
        formField: this.$utils.getFormField(
          this,
          {
            groupName: '',
            workGroupType: ''
          },
          this.$ConfigCache.CacheConfig.cacheData[leftPageCode]
        ),
        // 回调方法对象
        callbackObj: {
          // 网格点击回调事件
          onRowClick: (currentRow) => {
            this.onLeftRowClick(currentRow)
          }
        }
      },

      // 右网格
      rightTable: {
        // 网格Ref
        tableRef: 'rightTableRef',
        // 网格Key
        oneTableKey: 'rightTable',
        // 网格查询API配置对象
        apiConfig: api.teamsTechnicianSettingTechnician,
        // 动态组件-按钮
        tableButtons: [
          {
            compKey: 'btnKey1',
            type: 'primary',
            size: 'small',
            clickEvent: () => this.query(this.rightTable.tableRef),
            text: '查询',
            name: 'search',
            position: 'right'
          },
          {
            compKey: 'btnKey2',
            disabled: true,
            type: '',
            size: 'small',
            name: 'add',
            clickEvent: () => this.techniciantion(),
            text: '新增技师', // 新增技师
            position: 'left'
          },
          {
            compKey: 'btnKey3',
            disabled: true,
            parentFileds: 'disabled:table',
            type: '',
            size: 'small',
            clickEvent: () => this.pass(),
            text: '作废', // err
            name: 'reject',
            position: 'left'
          }
        ],
        // 动态组件-查询条件
        tableComponents:
          this.$ConfigCache.CacheConfig.cacheData[rightPageCode] &&
          this.$ConfigCache.CacheConfig.cacheData[rightPageCode].tableComponents
            .length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[rightPageCode]
              .tableComponents
            : [
              {
                compKey: 'compKey1',
                span: 12,
                labelName: '员工编号：',
                codeField: 'empCode',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                isMust: true
              },
              {
                compKey: 'compKey2',
                span: 12,
                labelName: '员工姓名：',
                codeField: 'empName',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                isMust: true
              }
            ],
        // 动态生成网格列
        tableCols:
          this.$ConfigCache.CacheConfig.cacheData[rightPageCode] &&
          this.$ConfigCache.CacheConfig.cacheData[rightPageCode].tableCols
            .length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[rightPageCode].tableCols
            : [
              {
                prop: 'empCode',
                label: '员工编号',
                width: null,
                align: 'center'
              },
              {
                prop: 'empName',
                label: '员工姓名',
                width: null,
                align: 'center'
              },
              {
                prop: 'deptName',
                label: '部门',
                width: null,
                align: 'center'
              },
              {
                prop: 'stationName',
                label: '岗位',
                width: null,
                align: 'center'
              },
              {
                prop: 'genderName',
                label: '性别',
                width: null,
                align: 'center'
              },
              {
                prop: 'isEnableCn',
                label: '是否在职',
                width: null,
                align: 'center'
              }
            ],
        // 表单数据
        formField: this.$utils.getFormField(
          this,
          {
            empName: '',
            empCode: ''
          },
          this.$ConfigCache.CacheConfig.cacheData[rightPageCode]
        ),
        // 排除表单查询条件
        unFormField: {
          empName: '',
          empCode: ''
        },
        // 回调方法对象
        callbackObj: {
          // 删除工程师
          onCheckSelectChange: (selection) => {
            this.selectiondata = selection
            this.onCheckSelectChange1(selection)
          },
          // 网格点击回调事件
          onRowClick: (currentRow) => {
            this.onRightRowClick(currentRow)
          }
        }
      }
    }
  },
  mounted() {
    this.query(this.leftTable.tableRef)
  },
  methods: {
    // 左边网格行点击
    onLeftRowClick(currentRow) {
      console.log("111111111111",currentRow)
      // 复制对象 1(默认):创建、2:清空、3:不操作
      if (currentRow) {
        this.rightTable.tableButtons[1].disabled = false
        this.addRow = currentRow
        this.rightTable.formField.repairGroupId = currentRow.repairGroupId
        // this.$utils.deepClone(this.rightTable.formField, repairGroupId, "1")
        // console.log(this.$utils.deepClone(this.rightTable.formField, repairGroupId, "1"))
        // debugger
        this.query(this.rightTable.tableRef, true)
      }
      this.resetRight()
    },
    // 右边网格行点击
    onRightRowClick(currentRow) {
      // 复制对象 1(默认):创建、2:清空、3:不操作
      this.$utils.deepClone(this.rightTable.formField, currentRow, '3')
    },
    // 重置右网格查询条件
    resetRight(tableRef) {
      // 复制对象 1(默认):创建、2:清空、3:不操作
      this.$utils.deepClone(
        this.rightTable.formField,
        this.rightTable.unFormField,
        '3'
      )
    },
    // 技工多选
    onCheckSelectChange1(selection) {
      const isCheck = selection && selection.length > 0
      this.rightTable.tableButtons[2].disabled = !isCheck
    },
    // 修改班组获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(this.$refs[this.leftTable.tableRef].list[index])
    },
    // 停用班组获取数据
    delet(index) {
      this.editRowData = this.$utils.deepCopy(this.$refs[this.leftTable.tableRef].list[index])
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.deleteTeam,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.editRowData
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.query(this.leftTable.tableRef)
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: 'warn',
            uration: 1000
          })
        }
      })
    },
    // 作废技师获取数据
    pass() {
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.DeleteTechnician,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.selectiondata
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        debugger
        if (response.result === '1') {
          this.$message({
            message: response.msg /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.query(this.rightTable.tableRef)
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: 'warn',
            uration: 1000
          })
        }
      })
    },
    addTeam() {
      this.editPopupsState = 'add'
      this.editPopupsVisible = true
      this.editRowData = {}
    },
    // 技师弹窗
    techniciantion() {
      this.technicianEditVisible = true
      this.technicianEditKey += '1'
    },
    // 技师弹窗关闭
    sendCodeClose() {
      this.technicianEditVisible = false
      this.technicianEditKey += '1'
      this.rightTable.formField.repairGroupId = this.addRow.repairGroupId
      this.query(this.rightTable.tableRef)
    },
    close(type) {
      this.editPopupsVisible = type
      this.query(this.leftTable.tableRef)
    },
    // 保存
    save(tableRef) {
      let that = this;
      if (that.$refs.rightTableRef.currentRow === null || undefined) {
        that.rightTable.formField.column1 = "";
      } else {
        that.rightTable.formField.column1 =
          that.$refs.rightTableRef.currentRow.lookupValueCode;
      }

      if (that.rightTable.formField.isEnable === "" || undefined) {
        that.$message({
          message: "是否启用不能为空",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      // validpopups 组件弹窗  validpage 表单查询
      that.$utils.validataMoth(that, "validpage", null, tableRef);
      // if (that.valid) {
      let queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: orgApis.deleteTeam,
        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          isEnable:"1",
          //当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: that.rightTable.formField,
        },
      };
      //转换了中台请求格式数据
      var paramD = that.$getParams(queryObj);
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === "0") {
          return;
        }
        var getResult = response;
        if (getResult.result === "1") {
          that.$message({
            message: getResult.msg,
            type: "success",
            duration: 2000,
          });
          // 重置表单
          that.resetRight(tableRef);
          // 重新加载
          that.onLeftRowClick(null);
        } else {
          that.$message({
            message: getResult.msg,
            type: "warning",
            duration: 2000,
          });
        }
      });
      // }
    },
    // 获取值
    // getCompValue(val, index, row) {
    //   console.info(val);
    //   console.info(index);
    //   console.info(row);
    // },
  }
}
</script>
